'use strict'

var http = require("http");
var https = require('https');
var fs = require('fs');
var socketIo = require('socket.io');
var log4js = require('log4js');

var express = require('express');
var serveIndex = require('serve-index');



//配置日志
log4js.configure({
   appenders: {
       file: {
           type: 'file',
           filename: 'app.log',
           layout: {
               type: 'pattern',
               pattern: '%r %p - %m',
           }
       }
   },
   categories: {
      default: {
         appenders: ['file'],
         level: 'debug'
      }
   }
});


var logger = log4js.getLogger();
var USERCOUNT = 3;   //限制房间人数

var app = express();
app.use(serveIndex('./public'));
app.use(express.static('./public'));



//配置web服务
/*http.createServer(function (request, response) {
  
   response.writeHead(200, {'Content-Type': 'text/plain'});  
   response.end('Hello World\n');

}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');*/
var http_server = http.createServer(app);
http_server.listen(8081);

var options = {
	key : fs.readFileSync('./cert/www.iaiia.site.key'),
	cert: fs.readFileSync('./cert/www.iaiia.site_bundle.pem')
}
var https_server = https.createServer(options, app);
https_server.listen(443);


//绑定socket监听
//var io = socketIo.listen(https_server);
var io = require('socket.io')(https_server);
io.on('connection', (socket)=>{

	socket.on('message', (room, data)=>{
		socket.to(room).emit('message',room, data);
	});
	  
	socket.on('join', (room)=>{
		socket.join(room);

		//console.log(io.sockets.adapter.rooms.has(room));//房间是否存在
		//var myRoom = io.sockets.adapter.rooms[room];		
		//var users = (myRoom)? Object.keys(myRoom.sockets).length : 0;
		var users = io.sockets.adapter.rooms.get(room).size;
		
		logger.debug('the user number of room is: ' + users);

		if(users < USERCOUNT){
			socket.emit('joined', room, socket.id); 
			if(users > 1){
				socket.to(room).emit('otherjoin', room, socket.id);//发给除自己之外的房间内的所有人
			}
		
		}else{
			socket.leave(room);	
			socket.emit('full', room, socket.id);
		}
		//socket.emit('joined', room, socket.id); //发给自己
		//socket.broadcast.emit('joined', room, socket.id); //发给除自己之外的这个节点上的所有人
		//io.in(room).emit('joined', room, socket.id); //发给房间内的所有人
	});

	socket.on('leave', (room)=>{
		var myRoom = io.sockets.adapter.rooms[room]; 
		var users = (myRoom)? Object.keys(myRoom.sockets).length : 0;
		logger.debug('the user number of room is: ' + (users-1));
		//socket.emit('leaved', room, socket.id);
		//socket.broadcast.emit('leaved', room, socket.id);
		socket.to(room).emit('bye', room, socket.id);
		socket.emit('leaved', room, socket.id);
		//io.in(room).emit('leaved', room, socket.id);
	});

});



